﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;
using DiscreteEventModel;
using DiscreteEventModel.Common;

namespace SpikingNeuralNetwork.Model {

    public partial class NeuralNetwork {

        public abstract class NeuralAgent : DiscreteEvent<NeuralNetwork>.Agent, IBinarySerializable {
            public StreamBase.Token ID { get; private set; }

            protected NeuralAgent(DiscreteEvent<NeuralNetwork>.IRuntime runtime)
                : base(runtime) {
                this.ID = runtime.Context.Backstore.Add(this);
                runtime.Context.ActiveAgents.Add(this.ID, this);
            }

            protected override void OnDispose(NeuralNetwork network) {
                if(network.InactiveAgents.TryAdd(this.ID, this)) {
                    network.ActiveAgents.Remove(this.ID);
                }
                if(network.InactiveAgents.Count >= 2048) {
                    network.Dump();
                }
            }

            public virtual void Serialize(BinaryWriter writer) {
                this.ID = (writer.BaseStream as StreamBase.InputStream).Token;
            }

            public virtual bool Deserialize(BinaryReader reader) {
                this.ID = (reader.BaseStream as StreamBase.OutputStream).Token;
                return true;
            }
        }
    }
}
